package me.sunpeng.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;

/**
 * @author sp
 */
public class ServerSocketChannelDemo {
    public static void main(String[] args) throws IOException, InterruptedException {

        //创建一个端口号
        int port = 8888;

        //buffer
        ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes());

        //ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();

        //绑定
        ssc.socket().bind(new InetSocketAddress(port));

        //设置非阻塞模式
        ssc.configureBlocking(false);

        //监听连接
        while (true){
            System.out.println("正在等待连接");
            SocketChannel sc = ssc.accept();
            if (sc == null) {
                System.out.println("无连接");
                TimeUnit.SECONDS.sleep(2);
            }else {
                System.out.println("有连接");
                System.out.println("地址来自 "+sc.socket().getRemoteSocketAddress());
                //指针0
                buffer.rewind();
                sc.write(buffer);
                sc.close();
            }
        }

    }
}
